import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import nprogress from 'nprogress'
import { createDiscreteApi } from 'naive-ui'
import { router } from '@/router/index'


const { message, dialog } = createDiscreteApi(['message', 'dialog'])

// 显示全屏loading
export function showFullLoading() {
  nprogress.start()
}

// 隐藏全屏loading
export function hideFullLoading() {
  nprogress.done()
}

// 侧边消息提示
export function toast(message, type = 'success', dangerouslyUseHTMLString = true) {
  ElNotification({
    message,
    type,
    dangerouslyUseHTMLString,
    duration: 3000,
  })
}

// 顶部消息提示
export function Toast(text, type = 'success') {
  message[type](text)
}

// 顶部消息提示
export function ELToast(text, type = 'success') {
  ElMessage({
    message: text,
    type,
  })
}

// 重要确认提示
export function showModal(content = '提示内容', type = 'warning', positiveText = '确定', negativeText = '取消', callBackSuccess, callBackError) {
  dialog.warning({
    content,
    positiveText,
    negativeText,
    onPositiveClick: () => {
      if (callBackSuccess && typeof callBackSuccess == 'function') callBackSuccess()
    },
    onNegativeClick: () => {
      if (callBackError && typeof callBackError == 'function') callBackError()
    }
  })
}


// element的确认提示
export function showModalEle(content = '提示内容', type = 'Warning', positiveText = '确定', negativeText = '取消', callBackSuccess, callBackError) {
  ElMessageBox.confirm(
    content,
    type,
    {
      confirmButtonText: positiveText,
      cancelButtonText: negativeText,
      type: 'warning',
    }
  )
    .then(() => {
      if (callBackSuccess && typeof callBackSuccess == 'function') callBackSuccess()
    })
    .catch(() => {
      if (callBackError && typeof callBackError == 'function') callBackError()
    })
}




// 弹出输入框
export function showPrompt(tip, value = '') {
  return ElMessageBox.prompt(tip, '', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputValue: value,
  })
}




// 单纯的确认提示
// export function showModal(content = "提示内容",type = "warning",title = ""){
//     return ElMessageBox.confirm(
//         content,
//         title,
//         {
//           confirmButtonText: '确认',
//           // cancelButtonText: '取消',
//           type,
//         }
//       )
// }

// 将query对象转成url参数
export function queryParams(query) {
  const q = []
  for (const key in query) {
    if (query[key])
      q.push(`${key}=${encodeURIComponent(query[key])}`)
  }
  let r = q.join('&')
  r = r ? (`?${r}`) : ''
  return r
}

// 添加厂商id
export function addcsid(url) {
  const userStore = useUserStore()
  let u
  if (userStore.userInfo.csid) {
    u = url + '/' + userStore.userInfo.csid
  } else {
    u = url
  }
  console.log(u)
  console.log(userStore.userInfo)
  return u
}


// 上移
export function useArrayMoveUp(arr, index) {
  swapArray(arr, index, index - 1)
}

// 下移
export function useArrayMoveDown(arr, index) {
  swapArray(arr, index, index + 1)
}

function swapArray(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0]
  return arr
}

export function againGroup(data, num) {
  const result = []
  for (let i = 0, len = data.length; i < len; i += num)
    result.push(data.slice(i, i + num))

  return result
}

// 阻止页面滚动
export function stop() {
  const box = function (e) { passive: false }
  document.body.style.overflow = 'hidden'
  document.addEventListener('touchmove', box, false)
}
// 允许页面滚动
export function move() {
  const box = function (e) { passive: false }
  document.body.style.overflow = '' // 出现滚动条
  document.removeEventListener('touchmove', box, false)
}

export const foreachTree = (data, callback, childrenName = 'children') => {
  for (let i = 0; i < data.length; i++) {
    callback(data[i])
    if (data[i][childrenName] && data[i][childrenName].length > 0)
      foreachTree(data[i][childrenName], callback, childrenName)
  }
}

export function trimAll(ele) {
  if (typeof ele === 'string') return ele.split(/[\t\r\f\n\s]*/g).join('')
  else console.error(`${typeof ele} is not the expected type, but the string type is expected`)
}

export const getRandomValue = array => array[Math.floor(Math.random() * array.length)]

export const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]))

export function randomString(length) {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let result = ''
  for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)]
  return result
}

export const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min



export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  const n = !isFinite(+number) ? 0 : +number
  const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
  const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
  const dec = typeof dec_point === 'undefined' ? '.' : dec_point
  let s = ''
  const toFixedFix = function (n, prec) {
    const k = Math.pow(10, prec)
    return '' + Math.ceil(n * k) / k
  }
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  const re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}






export const deepCopy = (obj, hash = new WeakMap()) => {
  if (obj instanceof Date) {
    return new Date(obj);
  }
  if (obj instanceof RegExp) {
    return new RegExp(obj);
  }
  if (hash.has(obj)) {
    return hash.get(obj);
  }
  let allDesc = Object.getOwnPropertyDescriptors(obj);
  let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);
  hash.set(obj, cloneObj);
  for (let key of Reflect.ownKeys(obj)) {
    if (obj[key] && typeof obj[key] === "object") {
      cloneObj[key] = deepCopy(obj[key], hash);
    } else {
      cloneObj[key] = obj[key];
    }
  }
  return cloneObj;
};




// 176 **** 3399
export function hideMobile(mobile, sign = '') {
  return String(mobile).replace(/^(\d{3})\d{4}(\d{4})$/, `$1${sign}****${sign}$2`)
}




// 176-1345-3399
export const formatPhone = (str, sign = '-') => String(str).replace(/(\W|\s)/g, "").split(/^(\d{3})(\d{4})(\d{4})$/).filter(item => item).join(sign)





// 复制
export const copyToClipboard = (content) => {
  const textarea = document.createElement("textarea")
  textarea.value = content
  document.body.appendChild(textarea)
  textarea.select()
  document.execCommand("Copy")
  textarea.remove()
}
